﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using TSQLPARSER;

namespace Sample
{
    class Program
    {

        StreamWriter WriteErrors = new StreamWriter("ParsingErrors.txt");
        static void Main(string[] args)
        {

            new Program().startProcess();
        }
        private void startProcess()
        {


            DirectoryInfo dMain = new DirectoryInfo(@"C:\DBSCRIPTS");
            Loop(dMain);
        }

        StringBuilder AllChanges = new StringBuilder();
        private void Loop(DirectoryInfo d)
        {
            foreach (DirectoryInfo dchild in d.GetDirectories())
            {
                Loop(dchild);
            }

            foreach (FileInfo f in d.GetFiles("*.SQL"))
            {
                Console.WriteLine("Processing " + f.Name);

                try
                {

                    File.WriteAllText(Path.ChangeExtension(f.FullName, "TC"), TableColumns(File.ReadAllText(f.FullName)));
                }
                catch (Exception ex)
                {
                    WriteErrors.WriteLine(f.FullName);
                }
            }

        }


      
        private StringBuilder TableColumns(string SqlText)
        {
            xParser xp = new xParser();
            xp.Parse(SqlText);

            //List<xStatement> xStmtlist = xp.ParsedOutput;
            Dictionary<int, List<xStatement>> GroupedOutput = xp.GroupedOutput;
            StringBuilder strOut = new StringBuilder();
            List<string> Unique = new List<string>();
            foreach (KeyValuePair<int, List<xStatement>> Kpair in GroupedOutput)
            {
                if (Kpair.Value.Count == 0) continue;

                List<xStatement> xStmtlist = Kpair.Value;
                Dictionary<string, string> Table = new Dictionary<string, string>();
                List<xTable> TablesUsed = new List<xTable>();

                xStatement XOneSingleStmt = new xStatement() { xColumnList = new List<xColumn>(), xTableList = new List<xTable>() };


                xStmtlist.ForEach(delegate(xStatement xt)
                {
                    
                    xt.xTableList.ForEach(delegate(xTable tb) { TablesUsed.Add(tb); XOneSingleStmt.xTableList.Add(tb); });
                    xt.xColumnList.ForEach(delegate(xColumn xc) { XOneSingleStmt.xColumnList.Add(xc); });
                    

                }
                );


                xStmtlist.ForEach(delegate(xStatement xt)
                {
                    AssociateAliasperStatement(xt, XOneSingleStmt);
                }
               );
                

                xStatement stm = XOneSingleStmt;

                foreach (xTable Tbx in TablesUsed)
                {
                    if (!Unique.Contains(Tbx.Tbltype.ToUpper() + "." + Tbx.TableName.ToUpper()))
                    {
                        strOut.AppendLine("<" + Tbx.Tbltype + ">-->" + Tbx.TableName.ToUpper());
                        Unique.Add(Tbx.Tbltype.ToUpper() + "." + Tbx.TableName.ToUpper());
                    }

                }

                XOneSingleStmt.xColumnList.ForEach(delegate(xColumn xc)
                {
                    if (!Unique.Contains(xc.Table.ToUpper() + "." + xc.Column.ToUpper()))
                    {
                        strOut.AppendLine(xc.Table.ToUpper() + "." + xc.Column.ToUpper());
                        Unique.Add(xc.Table.ToUpper() + "." + xc.Column.ToUpper());
                    };
                });

                
            }

            return strOut;    
            
        }

        private void AssociateAliasperStatement(xStatement xt,xStatement combo)
        {
            foreach (xColumn Xc in xt.xColumnList)
            {
                xTable tfb = xt.xTableList.Find(delegate(xTable tb) { return tb.Alias == Xc.TableAlias && !string.IsNullOrEmpty(Xc.TableAlias); });
                if (tfb == null)
                    tfb = xt.xTableList.Find(delegate(xTable tb) { return tb.TableName == Xc.TableAlias; });
                if (tfb != null)
                {
                    Xc.Table = tfb.TableName;
                }
                else
                {
                    tfb = combo.xTableList.Find(delegate(xTable tb) { return (tb.Alias == Xc.TableAlias && !string.IsNullOrEmpty(Xc.TableAlias)); });
                    if (tfb == null)
                        tfb = combo.xTableList.Find(delegate(xTable tb) { return tb.TableName == Xc.TableAlias; });
                    if (tfb != null)
                    {
                        Xc.Table = tfb.TableName;
                    }
                    else
                    {
                        Xc.Table = "";
                    }
 
                }


            }

        }

     

     
    }
}
